package com.tanhua.dubbo.api;

import com.tanhua.dubbo.api.db.UserInfoApi;
import com.tanhua.dubbo.api.mongo.RecommendUserApi;
import com.tanhua.model.db.User;
import com.tanhua.model.db.UserInfo;
import com.tanhua.model.mongo.RecommendUser;
import com.tanhua.model.vo.RecommendUserQueryParam;
import com.tanhua.model.vo.PageResult;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

@DubboService
public class RecommendUserApiImpl implements RecommendUserApi {


    @Autowired
    private MongoTemplate mongoTemplate;



    /**
     * 获取今日佳人
     *
     * @return
     */
    @Override
    public RecommendUser getTodayBest(Long userId){
        Query query = new Query();
        query.addCriteria(Criteria.where("toUserId").is(userId));
        query.with(Sort.by(Sort.Order.desc("score")));
        RecommendUser recommendUser = mongoTemplate.findOne(query, RecommendUser.class);
        return recommendUser;
    }

    /**
     * 佳人信息
     *
     * @param id
     * @return
     */
    @Override
    public RecommendUser getBast(Long id,Long userId) {
        Query query = new Query();
        query.addCriteria(Criteria.where("userId").is(id).and("toUserId").is(userId));
        RecommendUser recommendUser = mongoTemplate.findOne(query, RecommendUser.class);
        return recommendUser;
    }

    /**
     * 获取推荐列表
     */
    @Override
    public PageResult getrecommenDation(User user, RecommendUserQueryParam recommendUserQueryParam) {
        long start = (recommendUserQueryParam.getPage() -1) * recommendUserQueryParam.getPagesize();
        Long pageSize = recommendUserQueryParam.getPagesize();
        List<RecommendUser> list = new ArrayList<>();
        //1. 构建查询条件
        Query query = new Query(Criteria.where("toUserId").is(user.getId()));
        //2. 查询符合条件的总数
        long total = mongoTemplate.count(query, RecommendUser.class);
        //3. 计算开始行号
        //4. 总数>开始行号
        if (total > start) {
            //5. 设置分页参数
            query.skip(start).limit(pageSize.intValue());
            query.with(Sort.by(Sort.Order.desc("score")));
            //6. 分页查询
            list = mongoTemplate.find(query, RecommendUser.class);
        }

        //7. 构建pageResult再返回
        return new PageResult(recommendUserQueryParam.getPage(), pageSize, total, list);
    }


}
